import { listMyClassInfoVoByPageUsingPost } from '@/services/backend/classInfoController';
import {
  listTrainingPlanByPageUsingPost,
  updateTrainingPlanUsingPost,
} from '@/services/backend/trainingPlanController';
import {
  listUserClassRelationVoByPageUsingPost,
  listUserIdListByClassIdListUsingPost,
} from '@/services/backend/userClassRelationController';
import {
  deleteUserTrainingPlanRelationUsingPost,
  listUserTrainingPlanRelationVoByPageUsingPost,
} from '@/services/backend/userTrainingPlanRelationController';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { Button, message, Space, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import CreateModal from './components/CreateModal';
import UpdateModal from './components/UpdateModal';

interface TableRuleListItem extends API.TrainingRule {
  status: string;
}

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  const [currentRow, setCurrentRow] = useState<API.UserTrainingPlanRelationVO>();

  const [planEnumMap, setPlanEnumMap] = useState<Map<string, string>>(new Map());

  const [userEnumMap, setUserEnumMap] = useState<Map<string, string>>(new Map());

  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]); // 用于管理展开的行

  const loadPlanList = async () => {
    try {
      const { data, code } = await listTrainingPlanByPageUsingPost({});
      if (code === 0 && data?.records) {
        // 构建 userEnumMap
        const userMap = new Map<string, string>();
        data.records.forEach((plan: API.TrainingPlan) => {
          if (plan.id && plan.planName) {
            userMap.set(plan.id.toString(), plan.planName); // 假设 user 对象有 id 和 name 属性
          }
        });
        setPlanEnumMap(userMap);
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  const loadUserList = async () => {
    try {
      //获取classIdList
      // @ts-ignore
      let classIdList = [];
      const res = await listMyClassInfoVoByPageUsingPost({});
      if (res.data) {
        classIdList = res?.data?.records?.map((classInfo) => classInfo.id) ?? [];
      }

      if (classIdList.length === 0) {
        console.log('enter null');
        return true;
      }

      const { data, code } = await listUserClassRelationVoByPageUsingPost({
        role: 'student',
      });

      const filterData = data?.records?.filter((userClass) => {
        // @ts-ignore
        return classIdList.includes(userClass.classInfo?.id);
      });

      const newData = filterData?.map((userClass) => {
        return {
          ...userClass.user,
          classInfo: userClass.classInfo,
        };
      });

      if (code === 0 && newData) {
        // 构建 userEnumMap
        const userMap = new Map<string, string>();
        newData.forEach((user) => {
          if (user?.id && user.username) {
            userMap.set(user.id.toString(), user.username); // 假设 user 对象有 id 和 name 属性
          }
        });
        setUserEnumMap(userMap);
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  useEffect(() => {
    loadUserList();
    loadPlanList();
  }, []);

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.UserTrainingPlanRelation) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteUserTrainingPlanRelationUsingPost({
        id: row.id,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  /**
   *  Complete node
   * @zh-CN 任务完成,修改status
   *
   * @param row
   */
  const handleComplete = async (row: API.TrainingRuleDto) => {
    const hide = message.loading('正在更新');
    if (!row) return true;

    // 获取当前行的规则列表
    const ruleList = currentRow?.trainingPlan?.ruleList || [];

    // 更新对应的 trainingRuleId 的状态
    const updatedRuleList = ruleList.map((rule) => {
      if (rule.trainingRuleId === row.trainingRuleId) {
        return { ...rule, status: 1 }; // 将状态更新为 1
      }
      return rule; // 保持其他规则不变
    });

    console.log('current', currentRow);

    try {
      await updateTrainingPlanUsingPost({
        id: currentRow?.trainingPlan?.id,
        ruleList: updatedRuleList,
      });
      hide();
      message.success('更新成功');
      setCurrentRow({
        ...currentRow,
        trainingPlan: {
          ...currentRow?.trainingPlan,
          ruleList: updatedRuleList,
        },
      });
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error(`更新失败: ${error.message}`);
      return false;
    }
  };

  const expandedRowRender = (record: API.UserTrainingPlanRelationVO) => {
    // 假设 record 中有一个属性 `rules`，它是一个数组，包含了与该行相关的规则数据
    //@ts-ignore
    const data: TableRuleListItem[] = record?.trainingPlan?.ruleList || []; // 从当前行获取规则数据

    const columns: ProColumns<TableRuleListItem>[] = [
      {
        title: '规则名称',
        dataIndex: 'ruleName',
        valueType: 'text',
      },
      {
        title: '状态',
        dataIndex: 'status',
        valueType: 'select',
        valueEnum: {
          0: { text: '未完成', status: '0' },
          1: { text: '已完成', status: '1' },
        },
      },
      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, record) => (
          <Space size={'middle'}>
            <Typography.Link
              type="success"
              onClick={() => {
                //@ts-ignore
                handleComplete(record);
              }}
            >
              完成任务
            </Typography.Link>
          </Space>
        ),
      },
    ];

    return (
      <ProTable
        rowKey="id"
        columns={columns}
        dataSource={data} // 使用从当前行获取的数据
        headerTitle={false}
        search={false}
        options={false}
        pagination={false}
      />
    );
  };

  const columns: ProColumns<API.UserTrainingPlanRelationVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '用户姓名',
      dataIndex: ['user', 'username'],
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '训练名称',
      dataIndex: ['trainingPlan', 'planName'],
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        active: { text: '正在进行', status: 'ongoing' },
        archived: { text: '已完成', status: 'completed' },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size={'middle'}>
          <Typography.Link
            key="config"
            onClick={() => {
              setUpdateModalVisible(true);
              setCurrentRow(record);
            }}
          >
            修改
          </Typography.Link>
          <Typography.Link
            type="danger"
            onClick={() => {
              handleDelete(record);
            }}
          >
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.UserTrainingPlanRelation>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="id" // 确保使用数据中的唯一标识字段
        expandable={{
          expandedRowRender,
          expandedRowKeys,
          onExpand: (expanded, record) => {
            console.log('setCurrentRow', record);
            setCurrentRow(record);
            if (expanded) {
              // 添加当前行id到展开数组
              //@ts-ignore
              setExpandedRowKeys([record.id]);
            } else {
              // 从展开数组中移除当前行id
              setExpandedRowKeys([]);
            }
          },
        }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        //@ts-ignore
        request={async (params, sort, filter) => {
          //1.先获取currentUser的创建过的class => classIdList
          //获取classIdList
          // @ts-ignore
          let classIdList = [];
          const res = await listMyClassInfoVoByPageUsingPost({});
          if (res.data) {
            classIdList = res?.data?.records?.map((classInfo) => classInfo.id) ?? [];
          }
          if (classIdList.length === 0) {
            return {
              success: 0,
              data: [],
              total: 0,
            };
          }

          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listUserTrainingPlanRelationVoByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.UserTrainingPlanRelationQueryRequest);

          //2.根据classIdList获取needUserList
          const needUserListRes = await listUserIdListByClassIdListUsingPost({
            //@ts-ignore
            classIdList,
          });

          const needUserIdList = needUserListRes?.data;

          //3.根据 needUserIdList 获取需要的数据
          const filterData = data?.records?.filter((userTrain) => {
            // @ts-ignore
            return needUserIdList.includes(userTrain.user?.id);
          });

          return {
            success: code === 0,
            data: filterData || [],
            total: Number(filterData?.length) || 0,
          };
        }}
        columns={columns}
      />
      {/*新增悬浮窗*/}
      <CreateModal
        modalVisible={createModalVisible}
        planEnumMap={planEnumMap}
        userEnumMap={userEnumMap}
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      {/*更新悬浮窗*/}
      <UpdateModal
        oldData={currentRow}
        modalVisible={updateModalVisible}
        planEnumMap={planEnumMap}
        userEnumMap={userEnumMap}
        columns={columns}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default TableList;
